<script setup>
import { ref, onMounted, computed } from "vue";
import axios from 'axios';
import { useStore } from 'vuex';

const store = useStore();

// 从 Vuex store 中获取用户数据
let user = computed(() => store.getters.getUser);

// 初始化用户数据
const datainit = () => {
  user=computed(() => store.getters.getUser);
  // 假设你有一个 API 来获取用户数据
  axios.post('/admin/users/findByPhone', { phone: user.value.phone })
      .then(response => {
        const userData = response.data.date;
        store.dispatch('updateUser', userData);
        pic.value = [{ url: userData.profilePicture }];
      });
};

onMounted(() => {
  datainit();
});

// 头像图片
const pic = ref([]);

// 上传头像
const afterRead = (file) => {
  const formData = new FormData();
  formData.append("file", file.file, file.file.name);
  axios.post("/admin/users/upload", formData).then(response => {
    user.value.profilePicture = response.data.date;
    console.log(user.value.profilePicture);
    pic.value = [{ url: user.value.profilePicture }];
  });
};

// 定义 onClickLeft 方法
const onClickLeft = () => {
  history.back();
};

// 定义 onClickRight 方法
const onClickRight = () => {
  axios.post('/admin/users/save', user.value)
      .then(response => {
        if (response.data.code == 200) {
          showToast('修改成功');
        } else {
          showToast('修改失败');
        }
      });
};

// 显示 toast 提示
const showToast = (message) => {
  // 这里可以实现显示 toast 的逻辑
  console.log(message);
};
</script>

<template>
  <van-nav-bar
      title="设置"
      left-text=""
      right-text="完成"
      left-arrow
      @click-left="onClickLeft"
      @click-right="onClickRight"
  />
  <div>
    <h6>更换头像</h6>
    <van-uploader :after-read="afterRead" max-count="1" reupload v-model="pic">
    </van-uploader>
  </div>
  <div>
    <h6>昵称</h6>
    <van-cell-group inset>
      <van-field v-model="user.username" label="" placeholder="请输入用户名" />
    </van-cell-group>
  </div>
  <div>
    <h6>简介</h6>
    <van-cell-group inset>
      <van-field v-model="user.info" label="" placeholder="请输入简介" />
    </van-cell-group>
  </div>
</template>

<style scoped>
</style>